package ext.tianma.MaterialClassification;

import java.io.Closeable;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
import java.lang.reflect.InvocationTargetException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import org.apache.poi.POIXMLDocument;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.json.JSONException;
import org.json.JSONObject;

import ext.tianma.bom.eco.BOMHelp;
import ext.tianma.bom.util.ClassificationUtil;
import ext.tianma.bom.util.DBUtil;
import ext.tianma.bom.util.GenericUtil;
import ext.tianma.bom.util.QueryUtil;
import ext.tianma.part.util.ClassifictionToSourcing;
import ext.tianma.part.util.IBAUtil;
import ext.tianma.workflow.WorkItemHelper;
import wt.csm.navigation.ClassificationNode;
import wt.csm.navigation.ClassificationStruct;
import wt.fc.Persistable;
import wt.fc.PersistenceHelper;
import wt.fc.PersistenceServerHelper;
import wt.fc.QueryResult;
import wt.fc.WTObject;
import wt.folder.Folder;
import wt.folder.FolderEntry;
import wt.folder.FolderHelper;
import wt.iba.definition.ReferenceDefinition;
import wt.iba.definition.StringDefinition;
import wt.iba.value.IBAHolder;
import wt.iba.value.IBAReferenceable;
import wt.iba.value.ReferenceValue;
import wt.iba.value.StringValue;
import wt.inf.container.WTContainer;
import wt.inf.container.WTContainerRef;
import wt.lifecycle.LifeCycleHelper;
import wt.lifecycle.State;
import wt.method.RemoteAccess;
import wt.method.RemoteMethodServer;
import wt.part.LineNumber;
import wt.part.Quantity;
import wt.part.QuantityUnit;
import wt.part.Source;
import wt.part.WTPart;
import wt.part.WTPartHelper;
import wt.part.WTPartMaster;
import wt.part.WTPartStandardConfigSpec;
import wt.part.WTPartUsageLink;
import wt.pds.StatementSpec;
import wt.query.QueryException;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.query.TableColumn;
import wt.type.TypeDefinitionForeignKey;
import wt.type.TypeDefinitionReference;
import wt.type.Typed;
import wt.type.TypedUtility;
import wt.type.TypedUtilityServiceHelper;
import wt.util.WTException;
import wt.util.WTPropertyVetoException;
import wt.vc.VersionControlHelper;
import wt.vc.config.ConfigHelper;
import wt.vc.config.LatestConfigSpec;
import wt.vc.views.View;
import wt.vc.views.ViewHelper;
import wt.vc.views.ViewReference;

public class CreatePartClassificationUtil implements RemoteAccess {
	public static String STATUTE_PATH = "/ptc/Windchill/codebase/ext/tianma/part/config/classifiEName.xlsx";
	private static String PartPath = "Default/AVL材料";
	private static String part_type = "wt.part.WTPart|cn.tianma.Virtualparts|cn.tianma.GlueIronIntegration";

	public static WTPart createRFQPart(String PartPath, String part_type, String strPartName, String numberForRFQPart, String firstClassification,
			WTPart avlPart) {
		System.out.println("create ing ======" + numberForRFQPart);
		WTPart newPart = null;
		// 获取容器
		WTContainer container = null;
		QueryResult qr;
		try {

			// 取得RFQ编号
			//String fileName = CreatePartClassificationUtil.getClassification(avlPart);
			//if (fileName.contains("BLU类")) {
			//	numberForRFQPart = numberForRFQPart + "_BLU";
			//} else if (fileName.contains("FPC&PCB")) {
			//	numberForRFQPart = numberForRFQPart + "_FPC&PCB";
			//} else if (fileName.contains("LENS类")) {
			//	numberForRFQPart = numberForRFQPart + "_LENS";
			//} else if (fileName.contains("TP类")) {
			//	numberForRFQPart = numberForRFQPart + "_TP";
			//}
			numberForRFQPart = numberForRFQPart+"_"+firstClassification;
			WTPart part = BOMHelp.getPart(numberForRFQPart, "", "");
			if (part == null) {
				qr = CreatePartClassificationUtil.getQueryResult(WTContainer.class, WTContainer.NAME, "物料库");

				while (qr.hasMoreElements()) {
					container = (WTContainer) qr.nextElement();
				}
				// 获取容器的引用
				WTContainerRef ref = ref = WTContainerRef.newWTContainerRef(container);
				// 获取文件夹
				Folder folder = wt.folder.FolderHelper.service.getFolder(PartPath, ref);
				wt.vc.views.View view = ViewHelper.service.getView("Design");
				ViewReference viewRef = ViewReference.newViewReference(view);

				TypeDefinitionReference typeDefinitionRef = TypedUtility.getTypeDefinitionReference(part_type);
				String number = DBUtil.getNextValue("WTDOCUMENTID_seq", 10);
				System.out.println("number=====>>" + number);
				System.out.println("numberForRFQPart==========>>" + numberForRFQPart);
				// 创建一个部件，编码与名称
				newPart = WTPart.newWTPart(numberForRFQPart, strPartName);
				// 为部件设置容器
				newPart.setContainer(container);
				// 为部件设置类型
				newPart.setTypeDefinitionReference(typeDefinitionRef);
				// 为部件设置view
				newPart.setView(viewRef);
				// 是否成品
				newPart.setEndItem(false);
				// 设置单位
				QuantityUnit unit = QuantityUnit.toQuantityUnit("PCS");
				newPart.setDefaultUnit(unit);
				// 设置来源
				Source source = Source.toSource("make");
				newPart.setSource(source);
				// 为此部件设置存贮位置
				FolderHelper.assignLocation((FolderEntry) newPart, folder);

				newPart = (WTPart) PersistenceHelper.manager.save(newPart);
			}else {
				newPart = part;
			}

			System.out.println("create sucessful ====>>>" + newPart.getNumber());
		} catch (WTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (WTPropertyVetoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return newPart;
	}

	/**
	 * 创建一个新的部件，类似的代码可以实现修改part的基本属性
	 * 
	 * @param number
	 *            部件的编码
	 * @param PartType
	 *            部件的类型，部件在windchill中可以自定义很多中类型
	 * @return
	 * @throws WTException
	 * @throws WTPropertyVetoException
	 */
	public static QueryResult getQueryResult(Class className, String attribute, String value) throws WTException {
		QueryResult qr = null;
		try {
			QuerySpec qs = new QuerySpec(className);
			SearchCondition sc = new SearchCondition(className, attribute, SearchCondition.EQUAL, value);
			qs.appendWhere(sc);
			qr = PersistenceHelper.manager.find(qs);

		} catch (Exception e) {
			// TODO: handle exception
		}
		return qr;
	}

	/***
	 * 根据材料型号获取part
	 * 
	 * @param avlNumber
	 * @return
	 */
	public static WTPart getPartByIBAValue(String ibaName, String avlNumber) {
		System.out.println("验证是否存在=====》》》");
		WTPart part = null;
		QuerySpec qs;
		try {
			qs = new QuerySpec(WTPart.class);

			qs.setAdvancedQueryEnabled(true);
			// 通过类型的内部名称，获取类型定义的对象
			TypeDefinitionReference ref;
			ref = TypedUtilityServiceHelper.service.getTypeDefinitionReference("cn.tianma.RawMaterial");// 原材料
			long IdLong = ref.getKey().getBranchId();
			System.out.println("======>>>IdLong=====" + IdLong);

			// 通过类型的内部名称查询
			qs.appendWhere(
					new SearchCondition(WTPart.class,
							Typed.TYPE_DEFINITION_REFERENCE + "." + TypeDefinitionReference.KEY + "."
									+ TypeDefinitionForeignKey.BRANCH_ID,
							SearchCondition.EQUAL, IdLong),
					new int[] { 0 });
			qs.appendAnd();
			// IBA 属性过滤
			String condition = SearchCondition.EQUAL;
			qs.appendWhere(QueryUtil.getIBASearchCondition(WTPart.class, ibaName, avlNumber, condition),
					new int[] { 0 });
			System.out.println("qs=======>>" + qs);
			QueryResult qr = PersistenceHelper.manager.find(qs);
			qr = new LatestConfigSpec().process(qr);
			System.out.println("qr=======>>" + qr.size());
			while (qr.hasMoreElements()) {
				part = (WTPart) qr.nextElement();
				System.out.println("..............result:" + part.getNumber());
			}
		} catch (QueryException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (WTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return part;
	}

	public static WTPart getbpartByIBAValues(String ibaName, String ibaValue) {
		System.out.println("start  ==");
		WTPart part = null;
		QuerySpec qs;
		try {
			qs = new QuerySpec();
			int a = qs.appendClassList(WTPart.class, true);
			int b = qs.appendClassList(StringValue.class, true);
			int c = qs.appendClassList(StringDefinition.class, true);
			qs.setAdvancedQueryEnabled(true);
			String[] aliases = new String[3];
			aliases[0] = qs.getFromClause().getAliasAt(a);
			aliases[1] = qs.getFromClause().getAliasAt(b);
			aliases[2] = qs.getFromClause().getAliasAt(c);
			TableColumn tc1 = new TableColumn(aliases[0], "ida2a2");
			TableColumn tc2 = new TableColumn(aliases[1], "ida3a6");
			TableColumn tc3 = new TableColumn(aliases[1], "ida3a4");
			TableColumn tc4 = new TableColumn(aliases[2], "ida2a2");
			qs.appendWhere(new SearchCondition(tc4, "=", tc2), new int[] { a, b });
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(tc3, "=", tc1), new int[] { a, b });
			qs.appendAnd();
			qs.appendWhere(
					new SearchCondition(StringDefinition.class, StringDefinition.NAME, SearchCondition.EQUAL, ibaName),
					new int[] { c });
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(StringValue.class, StringValue.VALUE, SearchCondition.EQUAL, ibaValue),
					new int[] { b });
			System.out.println("qs========>>>" + qs);
			QueryResult qr = PersistenceHelper.manager.find((StatementSpec) qs);
			if (qr.hasMoreElements()) {
				Persistable ps[] = (Persistable[]) qr.nextElement();
				System.out.println("ps====>>" + ps);
				part = (WTPart) ps[0];
			}
		} catch (QueryException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (WTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return part;
	}

	/**
	 * 检验零件是否存在使用关系
	 * 
	 * @param parPart
	 *            父阶零件
	 * @param childPart
	 *            子阶零件
	 * @return 是否存在使用关系
	 */
	@SuppressWarnings("deprecation")
	public static boolean hasWTPartUsageLink(WTPart parPart, WTPart childPart) {
		boolean hasUsageLink = false;
		QueryResult qr = null;
		WTPartUsageLink link = null;
		WTPartMaster master = null;
		if (parPart != null && childPart != null) {
			try {
				qr = WTPartHelper.service.getUsesWTPartMasters(parPart);
				while (qr.hasMoreElements()) {
					link = (WTPartUsageLink) qr.nextElement();
					master = (WTPartMaster) link.getUses();
					if (childPart.getMaster().equals(master)) {
						hasUsageLink = true;
						break;
					}
				}
			} catch (WTException e) {
				e.printStackTrace();
			}
		}

		return hasUsageLink;
	}

	/**
	 * 
	 * @param classificationType
	 *            wt.part.WTPart
	 * @param classificationPath
	 *            name
	 * @param holder
	 *            pbo
	 * @throws Exception
	 */
	public static void setClassification(String classificationType, String classificationPath, IBAHolder holder)
			throws Exception {

		ReferenceDefinition refDefinition = getReferenceDefinition(classificationType);
		if (refDefinition == null)
			throw new Exception("No Classification Structure Found for " + classificationType);

		// IBAReferenceable referenceable = getClassificationNodeByPath(
		// classificationType, classificationPath);
		IBAReferenceable referenceable = getClassificationNodeByName(classificationPath);
		if (referenceable == null)
			throw new Exception("No Classification Path " + classificationPath + " found for " + classificationType);

		ReferenceValue refValue = ReferenceValue.newReferenceValue(refDefinition, holder, referenceable);
		PersistenceHelper.manager.save(refValue);

	}

	public static ClassificationNode getClassificationNodeByName(String classificationPath) throws Exception {
		QuerySpec spec = new QuerySpec(ClassificationNode.class);
		SearchCondition condition = new SearchCondition(ClassificationNode.class, ClassificationNode.NAME,
				SearchCondition.EQUAL, classificationPath);
		spec.appendWhere(condition, new int[0]);
		QueryResult result = PersistenceHelper.manager.find((StatementSpec) spec);
		while (result.hasMoreElements())
			return (ClassificationNode) result.nextElement();
		return null;
	}

	// wt.part.WTPart
	public static ReferenceDefinition getReferenceDefinition(String classificationType) throws Exception {
		QuerySpec spec = new QuerySpec(ClassificationStruct.class);
		SearchCondition condition = new SearchCondition(ClassificationStruct.class, ClassificationStruct.CLASS_NAME,
				SearchCondition.EQUAL, classificationType);
		spec.appendWhere(condition, new int[0]);
		QueryResult result = PersistenceHelper.manager.find((StatementSpec) spec);
		while (result.hasMoreElements()) {
			ClassificationStruct struct = (ClassificationStruct) result.nextElement();
			return struct.getRefDef();
		}
		return null;
	}

	public static String RemoteMethod(String partNumber) throws RemoteException, InvocationTargetException {
		String CLASSNAME = (CreatePartClassificationUtil.class).getName();
		Class argTypes[];
		Object svrArgs[];
		argTypes = (new Class[] { String.class });
		svrArgs = (new Object[] { partNumber });
		return (String) RemoteMethodServer.getDefault().invoke("getClassificationNode", CLASSNAME, null, argTypes,
				svrArgs);
	}

	/*
	 * 获取部件的分类节点
	 */
	@SuppressWarnings("deprecation")
	public static ClassificationNode getClassificationNode(WTPart part) {
		ClassificationNode classNode = null;
		QuerySpec queryspec;
		try {
			queryspec = new QuerySpec(wt.iba.value.ReferenceValue.class);
			queryspec.appendSearchCondition(new SearchCondition(wt.iba.value.ReferenceValue.class,
					"theIBAHolderReference.key", "=", part.getPersistInfo().getObjectIdentifier()));

			QueryResult queryresult = PersistenceHelper.manager.find(queryspec);
			while (queryresult.hasMoreElements()) {
				wt.iba.value.ReferenceValue value = (ReferenceValue) queryresult.nextElement();
				Persistable obj = value.getIBAReferenceableReference().getObject();
				if (obj instanceof ClassificationNode) {
					classNode = (ClassificationNode) obj;
				}
			}
		} catch (QueryException e) {
			e.printStackTrace();
		} catch (WTException e) {
			e.printStackTrace();
		}
		return classNode;
	}

	/*
	 * 获取部件分类节点的全路径名称，包括父节点名 如：电控零部件 \结构件 \成品电控柜
	 */
	@SuppressWarnings("deprecation")
	public static String getClassification(WTPart part) {
		ClassificationNode classNode = null;
		QuerySpec queryspec;
		try {
			queryspec = new QuerySpec(wt.iba.value.ReferenceValue.class);
			queryspec.appendSearchCondition(new SearchCondition(wt.iba.value.ReferenceValue.class,
					"theIBAHolderReference.key", "=", part.getPersistInfo().getObjectIdentifier()));

			QueryResult queryresult = PersistenceHelper.manager.find(queryspec);
			while (queryresult.hasMoreElements()) {
				wt.iba.value.ReferenceValue value = (ReferenceValue) queryresult.nextElement();
				Persistable obj = value.getIBAReferenceableReference().getObject();
				if (obj instanceof ClassificationNode) {
					classNode = (ClassificationNode) obj;
				}
			}
		} catch (QueryException e) {
			e.printStackTrace();
		} catch (WTException e) {
			e.printStackTrace();
		}

		// Debug.P("--------------------------------->>>>>>>>>>>>>>> classNode : " +
		// classNode);
		String classification = "";
		if (classNode != null) {
			ClassificationNode parentNode = null;
			List<ClassificationNode> classNodeLink = new ArrayList<ClassificationNode>(); // 用于存放部件的分类层级
			classNodeLink.add(classNode);
			// 倒序遍历上层分类
			while ((parentNode = classNode.getParent()) != null) {
				classNodeLink.add(parentNode);
				classNode = parentNode;
			}

			/**
			 * 获取完成的分类路径，例如：标准件/紧固件
			 */
			int linkSize = classNodeLink.size();
			StringBuffer classificationBuffer = new StringBuffer("");

			for (int i = linkSize - 1; i >= 0; i--) {
				ClassificationNode node = classNodeLink.get(i);
				classificationBuffer.append(node.getName());
				classificationBuffer.append("/");
			}
			classification = classificationBuffer.toString();
			if (classification.endsWith("/")) {
				classification = classification.substring(0, classification.length() - 1);
			}
		}
		return classification;
	}

	/**
	 * 根据part的编号获取对应的WTPartMaster
	 */
	public static WTPartMaster getWTPartMasterBYNumber(String number)

	{
		WTPartMaster master = null;
		try {

			QuerySpec qsMaster = new QuerySpec(WTPartMaster.class);
			SearchCondition sc = new SearchCondition(WTPartMaster.class, WTPartMaster.NUMBER, SearchCondition.EQUAL,
					number);
			qsMaster.appendSearchCondition(sc);
			QueryResult qrMaster = PersistenceHelper.manager.find(qsMaster);
			if (qrMaster.hasMoreElements()) {

				master = (WTPartMaster) qrMaster.nextElement();
			}

		} catch (WTException e) {
			e.printStackTrace();
		}
		return master;

	}

	/**
	 * 根据WTPartMaster获得最新版WTPart
	 * 
	 */
	public static WTPart getLatestPart(WTPartMaster partMaster) throws Exception {
		WTPart part = null;
		if (partMaster != null) {
			QueryResult qr = VersionControlHelper.service.allVersionsOf(partMaster);
			if (qr != null && qr.hasMoreElements()) {
				part = (WTPart) qr.nextElement();
			}
		}
		return part;
	}

	/**
	 * 获取分类属性值
	 * 
	 * @param number
	 * @return
	 */
	public static Map<String, String> getMaterialsClassification(String number) {
		JSONObject result = new JSONObject();
		Map<String, String> maps = new HashMap<String, String>();
		try {
			WTPart part = GenericUtil.getPart(number, "");
			if (part == null) {
				result.put("datalist", "");
			}
			// String classtype = (String) LWCUtil.getValue(part, "SemiFinishedGoodType");
			// System.out.println("=====getMaterialsClassification classtype:" + classtype);

			List<HashMap<String, String>> list = ClassificationUtil.getNodeIBAByPart2(part);
			JSONObject object = new JSONObject();
			for (HashMap<String, String> map : list) {
				String displayname = map.get("displayname");
				String value = map.get("value");
				String key = map.get("key");
				System.out.println("====displayname:" + displayname + "==key:" + key + "---value:" + value);
				object.put(displayname, value == null ? "" : value);
				maps.put(key, value);
			}
			result.put("datalist", object);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println("===getMaterialsClassification Exception:" + e);
			e.printStackTrace();
		}
		return maps;
	}

	public static String subStr(String str, int start) {
		if (str == null || str.equals("") || str.length() == 0)
			return "";
		if (start < str.length()) {
			return str.substring(start);
		} else {
			return "";
		}

	}

	/**
	 * 关闭资源
	 * 
	 * @param closeable
	 */
	public static void close(Closeable closeable) {
		try {
			if (closeable != null) {
				closeable.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 创建UsageLink方法
	 * 
	 * @param parentPart
	 * @param childPartMaster
	 * @param lineNumber
	 * @param hashtable
	 * @param Yield
	 *            良率
	 * @throws WTException
	 */
	private static void createWTPartUsageLink(WTPart parentPart, WTPartMaster childPartMaster, Hashtable hashtable) {
		if (parentPart == null || childPartMaster == null) {
			return;
		}
		WTPartUsageLink usageLink;
		try {
			parentPart = (WTPart) GenericUtil.checkout(parentPart);
			usageLink = WTPartUsageLink.newWTPartUsageLink(parentPart, childPartMaster);
			GenericUtil.checkin(parentPart);
			parentPart = (WTPart) PersistenceHelper.manager.refresh(parentPart);
		} catch (WTException e) {
			System.out.println("ERROR  createWTPartUsageLink: parentPart," + parentPart.getNumber()
					+ ";childPartMaster," + childPartMaster.getNumber());
			e.printStackTrace();
		} catch (WTPropertyVetoException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

	}

	/**
	 * 设置usageLink的单位数量
	 * 
	 * @param quantity
	 * @param usageLink
	 */
	private static void setQuantity(Quantity quantity, WTPartUsageLink usageLink) {
		if (quantity != null && !quantity.equals("")) {
			usageLink.setQuantity(quantity);
		}
	}

	/**
	 * 创建一个usageLink关系对象并且为其行号复制
	 * 
	 * @param lineNumber
	 * @param usageLink
	 * @throws WTException
	 */
	private static void setLineNumber(String lineNumber, WTPartUsageLink usageLink) throws WTException {
		if (lineNumber != null && !lineNumber.equals("")) {

			try {
				long lineNumberValue = Long.parseLong(lineNumber);
				LineNumber newLineNumber = LineNumber.newLineNumber(lineNumberValue);
				usageLink.setLineNumber(newLineNumber);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 根据编号和视图查询对应最新视图版本的零部件.
	 * 
	 * @author Harry Cao
	 * @param number
	 * @param view
	 * @return
	 * @throws WTException
	 */
	public static WTPart getWTPartByNumberAndView(String number, String view) throws WTException {
		WTPartMaster master = getWTPartMasterByNumber(number);
		if (master == null)
			return null;
		else
			return getWTPartByMasterAndView(master, view);
	}

	/**
	 * 根据零部件的编号查找零部件的主数据(master)
	 * 
	 * @author Harry Cao
	 * @param partNumber
	 * @return
	 * @throws WTException
	 */
	public static WTPartMaster getWTPartMasterByNumber(String partNumber) throws WTException {
		WTPartMaster master = null;
		QuerySpec qs = null;
		QueryResult qr = null;
		qs = new QuerySpec(WTPartMaster.class);
		// 定义搜索条件，以零部件编号方式在master中搜索
		SearchCondition sc = new SearchCondition(WTPartMaster.class, WTPartMaster.NUMBER, SearchCondition.EQUAL,
				partNumber);
		qs.appendSearchCondition(sc);
		qr = PersistenceHelper.manager.find(qs);
		if (qr.hasMoreElements()) {
			master = (WTPartMaster) qr.nextElement();
		}
		return master;
	}

	/**
	 * 根据零部件主数据(master)和视图获取对应最新版本零部件
	 * 
	 * @author Harry Cao
	 * @param master
	 * @param view
	 * @return
	 * @throws WTException
	 */
	public static WTPart getWTPartByMasterAndView(WTPartMaster master, String view) throws WTException {
		WTPart part = null;
		// 根据视图名称获取视图对象
		View viewObj = ViewHelper.service.getView(view);

		// 根据视图构造产品结构配置规范
		WTPartStandardConfigSpec standardConfig = WTPartStandardConfigSpec.newWTPartStandardConfigSpec(viewObj, null);
		try {
			standardConfig.setView(viewObj);
		} catch (WTPropertyVetoException wpve) {
			throw new WTException(wpve);
		}

		// 根据master和视图获取对应最新的视图版本零部件
		QueryResult qr1 = ConfigHelper.service.filteredIterationsOf(master, standardConfig);
		if (qr1.hasMoreElements()) {
			part = (WTPart) qr1.nextElement();
			if (!part.getViewName().equals(view))
				return null;
			System.out.println("部件的视图：" + part.getViewName());
		}

		return part;
	}

	public static String getPartUrlByNumber(String partNumber) {
		JSONObject ob = new JSONObject();
		try {
			WTPart avlPart = BOMHelp.getPart(partNumber, "", "");
			if (avlPart != null) {
				// 调用获取url方法
				String partUrl = WorkItemHelper.generateInfoPageURL(avlPart);
				System.out.println("====>>>partUrl==>>" + partUrl);
				ob.put("status", "sucess");
				ob.put("message", "创建成功！");
				ob.put("data", partUrl);
			} else {
				ob.put("status", "false");
				ob.put("message", "创建成功！");
				ob.put("data", "");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ob.toString();

	}

	/***
	 * 根据配置文件获取物料英文名称
	 * 
	 * @return
	 * @throws WTException
	 * @throws IOException
	 */
	public static String getPartEName(String partClassifictionName) throws IOException, WTException {

		String partENames = "";
		InputStream is = null;
		Workbook wb = null;
		Workbook workbook = null;
		System.out.println("CASCADE_PATH===>>" + STATUTE_PATH);
		is = new FileInputStream(STATUTE_PATH);

		System.out.println("=====>>>" + STATUTE_PATH);
		if (!is.markSupported()) {
			is = new PushbackInputStream(is, 8);
		}

		if (POIFSFileSystem.hasPOIFSHeader(is)) {
			// 2003及以下
			wb = new HSSFWorkbook(is);
		} else if (POIXMLDocument.hasOOXMLHeader(is)) {
			// 2007及以上
			wb = new XSSFWorkbook(is);
		} else {
			// 不是Excel
			throw new WTException("Incorrect configuration file path.");
		}

		workbook = wb;

		Sheet sheet = workbook.getSheetAt(0);
		Row row;
		Cell cell1, cell2, cell;
		String tempVal;

		// 第一行为表头，从第二行开始遍历
		for (int i = 1, rowNum = sheet.getLastRowNum(); i <= rowNum; i++) {
			if ((row = sheet.getRow(i)) != null) {
				// 遍历列
				String classifictionName = "";
				String partEName = "";
				int cellNum = row.getLastCellNum();
				String str = "";
				for (int j = 0; j <= cellNum; j++) {
					cell = row.getCell(j);
					cell1 = row.getCell(0);
					cell2 = row.getCell(1);
					System.out.println("cell1===>>" + cell1);
					System.out.println("cell2===>>" + cell2);
					if (cell1 == null || (tempVal = cell1.getStringCellValue()) == null || cell2 == null
							|| (tempVal = cell2.getStringCellValue()) == null) {
						str = "";
					} else {
						classifictionName = cell1.getStringCellValue();
						System.out.println("classifictionName====>>" + classifictionName);
						partEName = cell2.getStringCellValue();
						System.out.println("partEName====>>" + partEName);
						System.out.println("partClassifictionName====>>" + partClassifictionName);
						if (classifictionName.equals(partClassifictionName)) {
							partENames = partEName;
						}
					}
				}

			}
		}
		return partENames;
	}

	/***
	 * 创建胶铁一体的料
	 * 
	 * @param parentPart
	 * @return
	 * @throws Exception
	 */
	public static String createPartByJT(WTObject part) throws Exception {
		System.out.println("start into creaate JTYT=====>>>>");
		WTPart parentPart = null;
		if (part instanceof WTPart) {
			parentPart = (WTPart) part;
		}

		// 获取当前BOM对象，取出胶材和铁材
		List<WTPart> partList = readBOM(parentPart);
		WTPart JKPart = null;
		WTPart TKPart = null;
		for (int j = 0; j < partList.size(); j++) {
			WTPart strPart = partList.get(j);
			if (strPart.getName().contains("胶框塑胶粒子")) {
				JKPart = strPart;
			}
			if (strPart.getName().contains("金属框原材")) {
				TKPart = strPart;
			}
		}
		// 获取胶铁一体相关属性
		if (JKPart != null && TKPart != null) {
			System.out.println("start two  into =====>>");
			// 根据胶框和铁矿获取到想关联APL材料获取其相关属性
			IBAUtil ibaJKPart = new IBAUtil(JKPart);
			String ibaJKAPLNumber = ibaJKPart.getIBAValue("APLNumber");
			// 获取胶框的二级料号给胶铁一体框
			String twoPartNumberIba = ibaJKPart.getIBAValue("twosPartNumber");
			ibaJKAPLNumber = ibaJKAPLNumber.substring(0, 10);
			WTPart APLPartJK = BOMHelp.getPart(ibaJKAPLNumber, "", "");
			System.out.println("ibaTKAPLNumber====>>>" + ibaJKAPLNumber);
			IBAUtil ibaTKPart = new IBAUtil(TKPart);
			String ibaTKAPLNumber = ibaTKPart.getIBAValue("APLNumber");
			ibaTKAPLNumber = ibaTKAPLNumber.substring(0, 10);
			System.out.println("ibaTKAPLNumber====>>>" + ibaTKAPLNumber);
			WTPart APLPartTK = BOMHelp.getPart(ibaTKAPLNumber, "", "");
			if (APLPartJK == null || APLPartTK == null) {
				throw new WTException("没有获取到物料，请检查");
			}
			IBAUtil APLPartJKIba = new IBAUtil(APLPartJK);
			IBAUtil APLPartTKIba = new IBAUtil(APLPartTK);
			String supplier = APLPartJKIba.getIBAValue("Supplier") + "/" + APLPartTKIba.getIBAValue("Supplier"); // 原材料供应商
			System.out.println("supplier====>>" + supplier);
			String UsableRange = APLPartJKIba.getIBAValue("UsableRange") + "/"
					+ APLPartTKIba.getIBAValue("UsableRange"); // 使用范围
			String environmentalLevel = APLPartJKIba.getIBAValue("environmentalLevel") + "/"
					+ APLPartTKIba.getIBAValue("environmentalLevel"); // 环保等级
			String materialState = APLPartJKIba.getIBAValue("materialState") + "/"
					+ APLPartTKIba.getIBAValue("materialState"); // 材料状态
			String MaterialType = APLPartJKIba.getIBAValue("MaterialType") + "/"
					+ APLPartTKIba.getIBAValue("MaterialType"); // 材料型号
			String classifiJKPart = getClassifiByPart(JKPart);
			System.out.println("classifiJKPart===>>" + JKPart.getNumber() + ":" + classifiJKPart);
			String classifiTKPart = getClassifiByPart(TKPart);
			String classifiList = JKPart.getNumber() + ":" + classifiJKPart + ";" + TKPart.getNumber() + ":"
					+ classifiTKPart;
			System.out.println("classifiList===>>>" + classifiList);

			// 创建胶铁一体物料
			WTPart newPart = null;
			// 获取容器
			WTContainer container = null;
			QueryResult qr;
			try {
				qr = CreatePartClassificationUtil.getQueryResult(WTContainer.class, WTContainer.NAME, "物料库");

				while (qr.hasMoreElements()) {
					container = (WTContainer) qr.nextElement();
				}
				// SessionHelper.manager.getPrincipal();
				// SessionHelper.getPrincipal();
				// 获取容器的引用
				WTContainerRef ref = ref = WTContainerRef.newWTContainerRef(container);
				// 获取文件夹
				Folder folder = wt.folder.FolderHelper.service.getFolder(PartPath, ref);
				wt.vc.views.View view = ViewHelper.service.getView("Design");
				ViewReference viewRef = ViewReference.newViewReference(view);

				TypeDefinitionReference typeDefinitionRef = TypedUtility.getTypeDefinitionReference(part_type);
				// 获取物料编码
				String twoPartNumber = AVLPartCommandsUtils.generateRowXNNumber(JKPart, "PC");
				// 创建一个部件，编码与名称
				newPart = WTPart.newWTPart(twoPartNumber, "胶铁一体");
				// 为部件设置容器
				newPart.setContainer(container);
				// 为部件设置类型
				newPart.setTypeDefinitionReference(typeDefinitionRef);
				// 为部件设置view
				newPart.setView(viewRef);
				// 是否成品
				newPart.setEndItem(false);
				// 设置单位
				QuantityUnit unit = QuantityUnit.toQuantityUnit("PCS");
				newPart.setDefaultUnit(unit);
				// 设置来源
				Source source = Source.toSource("make");
				newPart.setSource(source);
				// 为此部件设置存贮位置
				FolderHelper.assignLocation((FolderEntry) newPart, folder);

				// 保存部件，切忌不要保存两次。经常在调用完本方法之后习惯性的再保存一次，这样会出现错误。
				newPart = (WTPart) PersistenceHelper.manager.save(newPart);
				System.out.println("create sucessful ====>>>" + newPart.getNumber());
				Quantity count = getWTPartUsageLink(parentPart, JKPart);
				System.out.println("count=====>>" + count);
				createUserLinkByPart(parentPart, newPart, count);

				// 更新胶铁一体部件属性
				IBAUtil iba = new IBAUtil(newPart);
				iba.setIBAValue("Supplier", supplier);
				iba.setIBAValue("UsableRange", UsableRange);
				iba.setIBAValue("environmentalLevel", environmentalLevel);
				iba.setIBAValue("materialState", materialState);
				iba.setIBAValue("MaterialType", MaterialType);
				iba.setIBAValue("classifictionList", classifiList);
				iba.setIBAValue("AndTK", TKPart.getNumber());
				iba.setIBAValue("AndJK", JKPart.getNumber());
				iba.setIBAValue("twosPartNumber", twoPartNumberIba);
				iba.updateIBAPart(newPart);
				newPart = (WTPart) LifeCycleHelper.service.setLifeCycleState(newPart, State.INWORK);
				PersistenceHelper.manager.refresh(newPart);

			} catch (WTException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (WTPropertyVetoException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvalidFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return "";

	}

	/***
	 * 获取bom结构 xin_gao1
	 * 
	 * @param part
	 * @param level
	 * @return
	 * @throws WTException
	 */
	private static List<WTPart> readBOM(WTPart part) throws WTException {
		List<WTPart> list = new ArrayList<WTPart>();
		QueryResult qr = PersistenceHelper.manager.navigate(part, WTPartUsageLink.USES_ROLE, WTPartUsageLink.class,
				false);
		while (qr.hasMoreElements()) {
			WTPartUsageLink link = (WTPartUsageLink) qr.nextElement();
			WTPartMaster childMaster = link.getUses();
			QueryResult iterationQr = VersionControlHelper.service.allVersionsOf(childMaster);
			WTPart childPart = (WTPart) iterationQr.nextElement();
			list.add(childPart);

			list.addAll(readBOM(childPart));

		}
		return list;
	}

	public static String getClassifiByPart(WTPart part) {

		String classifictionList = "";
		// 获取零部件分类

		try {
			Hashtable<String, String> values = new Hashtable<String, String>();
			ClassificationNode classificationNode = ClassificationUtil.getClassificationNode(part);
			if (classificationNode != null) {
				System.out.println("start == into ==--------" + classificationNode.getIBAReferenceableDisplayString());
				System.out.println("classificationNodeName===>>" + classificationNode.getName());
				String strList = ClassifictionToSourcing.getClassifictionIba(classificationNode.getName(), part);
				System.out.println("strList===>>" + strList);
				classifictionList = strList;
			}
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (WTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return classifictionList;

	}

	public static void createUserLinkByPart(WTPart parentPart, WTPart childPart, Quantity count) {
		try {
			WTPartMaster childPartMaster = (WTPartMaster) childPart.getMaster();
			WTPartUsageLink newlink = WTPartUsageLink.newWTPartUsageLink(parentPart, childPartMaster);
			// double quanty = Double.parseDouble(count);
			// QuantityUnit qu = null;
			// if (childPartMaster != null) {
			// qu = childPartMaster.getDefaultUnit();
			// }
			// Quantity qtity = Quantity.newQuantity(quanty, qu);
			newlink.setQuantity(count);
			PersistenceServerHelper.manager.insert(newlink);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static Quantity getWTPartUsageLink(WTPart parPart, WTPart childPart) {
		Quantity count = null;
		QueryResult qr = null;
		WTPartUsageLink link = null;
		WTPartMaster master = null;
		if (parPart != null && childPart != null) {
			try {
				qr = WTPartHelper.service.getUsesWTPartMasters(parPart);
				while (qr.hasMoreElements()) {
					link = (WTPartUsageLink) qr.nextElement();
					master = (WTPartMaster) link.getUses();
					if (childPart.getMaster().equals(master)) {
						count = link.getQuantity();
						break;
					}
				}
			} catch (WTException e) {
				e.printStackTrace();
			}
		}
		return count;

	}

}
